package services

import (
	"CampusRecruitment/pkg/models"
	"CampusRecruitment/pkg/types"
	"CampusRecruitment/pkg/types/errors"
	"CampusRecruitment/pkg/types/resps"
	"gorm.io/gorm"
)

func CreateNews(db *gorm.DB, news *models.News) (*resps.GetNewsListResp, error) {
	if err := db.Model(&models.News{}).Create(&news).Error; err != nil {
		return nil, errors.AutoDbErr(err)
	}
	return GetNewsById(db, news.Id)
}

func GetNewsById(db *gorm.DB, id models.Id) (*resps.GetNewsListResp, error) {
	news := resps.GetNewsListResp{}
	if err := db.Model(&models.News{}).Where("id", id).First(&news).Error; err != nil {
		return nil, errors.AutoDbErr(err)
	}
	return &news, nil
}

func DeleteNewsById(db *gorm.DB, id models.Id) error {
	news := models.News{}
	if err := db.Where("id", id).Delete(&news).Error; err != nil {
		return errors.AutoDbErr(err)
	}
	return nil
}

func UpdateNews(db *gorm.DB, form *types.UpdateNewsForm) (*resps.GetNewsListResp, error) {
	news := models.News{}
	if dbErr := db.Model(&news).Where("id", form.Id).Updates(models.News{
		Title:   form.Title,
		Content: form.Content,
		State:   "audit",
	}).Error; dbErr != nil {
		return nil, errors.AutoDbErr(dbErr)
	}
	return GetNewsById(db, form.Id)
}

func GetNewsList(db *gorm.DB, q string) *gorm.DB {
	return db.Model(&models.News{}).Where("state", "active").Where("title LIKE ? OR username LIKE ?",
		"%"+q+"%", "%"+q+"%").Order("updated_at")
}

func GetAllNews(db *gorm.DB, q string) *gorm.DB {
	return db.Model(&models.News{}).Where("title LIKE ? OR username LIKE ?",
		"%"+q+"%", "%"+q+"%").Order("updated_at")
}

func UpdateNewsStateById(db *gorm.DB, id models.Id, state string) error {
	return db.Model(&models.News{}).Where("id", id).Update("state", state).Error
}

func GetMyNewsByUserId(db *gorm.DB, form *types.GetMyNewsForm) *gorm.DB {
	return db.Model(&models.News{}).Where("user_id", form.Id).Where("title LIKE ? OR username LIKE ?",
		"%"+form.Q+"%", "%"+form.Q+"%").Order("updated_at")
}
